package com.mhc.suzuki.service.impl;

import com.mhc.haval.security.model.User;
import com.mhc.suzuki.bo.PaymentDetailBO;
import com.mhc.suzuki.bo.PaymentNotificationQueryBO;
import com.mhc.suzuki.bo.SubmitTaskBO;
import com.mhc.suzuki.constant.ErrorCodeEnum;
import com.mhc.suzuki.constant.OrderStatusEnum;
import com.mhc.suzuki.constant.PaymentRequestStatusEnum;
import com.mhc.suzuki.dal.mapper.ext.PaymentRequestExtMapper;
import com.mhc.suzuki.dal.model.OrderDO;
import com.mhc.suzuki.dal.model.PaymentRequestDO;
import com.mhc.suzuki.dal.query.OrderQuery;
import com.mhc.suzuki.dal.query.PaymentRequestQuery;
import com.mhc.suzuki.exception.SuzukiCommonException;
import com.mhc.suzuki.manager.OrderManager;
import com.mhc.suzuki.manager.PaymentRequestManager;
import com.mhc.suzuki.service.ApplyService;
import com.mhc.suzuki.service.PaymentNotificationService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by HW
 * on 2017/8/29 15:40.
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class PaymentNotificationServiceImpl implements PaymentNotificationService {

    @Autowired
    private PaymentRequestExtMapper paymentRequestExtMapper;

    @Autowired
    private OrderManager orderManager;

    @Autowired
    private ApplyService applyService;

    @Autowired
    private PaymentRequestManager paymentRequestManager;

    /**
     * 条件查询打款通知列表
     * @param paymentNotificationQueryBO 查询条件
     * @return
     * @throws SuzukiCommonException
     */
    @Override
    public List<PaymentNotificationQueryBO> queryPaymentNotificationQueryBOSByQuery(PaymentNotificationQueryBO paymentNotificationQueryBO) throws SuzukiCommonException {
        log.info("开始查询打款通知列表");
        //设置查询map
        Map<String, Object> queryMap = settQuery(paymentNotificationQueryBO);
        log.info(queryMap.toString());

        //查询
        return paymentRequestExtMapper.queryPaymentRequestByMap(queryMap);

    }


    /**
     * 查询打款通知列表总数
     * @param paymentNotificationQueryBO
     * @return
     * @throws SuzukiCommonException
     */
    @Override
    public Integer queryTotalCount(PaymentNotificationQueryBO paymentNotificationQueryBO) throws SuzukiCommonException{
        Map<String, Object> queryMap = settQuery(paymentNotificationQueryBO);
        log.info(queryMap.toString());
        return paymentRequestExtMapper.queryTotalCount(queryMap);
    }


    /**
     * 根据订单号查看打款通知详情
     * @param orderNo
     * @return
     * @throws SuzukiCommonException
     */
    @Override
    public PaymentDetailBO queryPaymentDetailByOrderNo(String orderNo) throws SuzukiCommonException{
        if (StringUtils.isBlank(orderNo)){
            return null;
        }
        return paymentRequestExtMapper.queryPaymentDetailByOrderNo(orderNo);
    }

    /**
     * 查询条件map设置
     * @param paymentNotificationQueryBO
     * @return
     */
    private Map<String, Object> settQuery(PaymentNotificationQueryBO paymentNotificationQueryBO){
        Map<String, Object> queryMap = new HashMap<>(64);
        queryMap.put("key", paymentNotificationQueryBO.getKey());//姓名,身份证号，订单号
        //queryMap.put("gmtCreate", paymentNotificationQueryBO.getGmtCreate().format(DateTimeFormatter.ISO_LOCAL_DATE));//申请时间
        queryMap.put("gmtStart", paymentNotificationQueryBO.getGmtStart());
        queryMap.put("gmtEnd", paymentNotificationQueryBO.getGmtEnd());
        queryMap.put("payeeBankId", paymentNotificationQueryBO.getPayeeBankId());
        queryMap.put("payeeBankName", paymentNotificationQueryBO.getPayeeBankName());//贷款银行名称
        queryMap.put("staffId", paymentNotificationQueryBO.getStaffId());//员工编号
        //queryMap.put("pageNo", paymentNotificationQueryBO.getPageNo());//页数
        queryMap.put("pageSize", paymentNotificationQueryBO.getPageSize());//每页显示条数

        /*计算pageOffset*/
        PaymentRequestQuery paymentRequestQuery = new PaymentRequestQuery();
        paymentRequestQuery.setPageNo(paymentNotificationQueryBO.getPageNo());
        paymentRequestQuery.setPageSize(paymentNotificationQueryBO.getPageSize());
        queryMap.put("pageOffset", paymentRequestQuery.getPageOffset());//偏移数

        return queryMap;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean remittance(PaymentDetailBO paymentDetailBO,SubmitTaskBO submitTaskBO,User logedUser) throws SuzukiCommonException {
        Boolean result = true;
        if (StringUtils.isBlank(paymentDetailBO.getOrderNo())){
            result = false;
        }

        /*更新订单状态*/
        OrderDO orderDO = new OrderDO();
        orderDO.setOrderStatus(OrderStatusEnum.ALREADY_PAYMENT.getCode());

        OrderQuery orderQuery = new OrderQuery();
        orderQuery.createCriteria().andOrderNoEqualTo(paymentDetailBO.getOrderNo())
                    .andOrderStatusNotEqualTo(OrderStatusEnum.CANCELLED.getCode())
                    .andOrderStatusEqualTo(OrderStatusEnum.PAYMENT_REQUEST.getCode());
        if(orderManager.updateByQuerySelective(orderDO, orderQuery) != 1){
            throw new SuzukiCommonException(ErrorCodeEnum.INSERT_OR_UPDATA_ERROR);
        }

        /*更新打款通知表*/
        PaymentRequestDO paymentRequestDO = new PaymentRequestDO();
        paymentRequestDO.setHandleStaffId(paymentDetailBO.getHandleStaffId());
        paymentRequestDO.setApplyStatus(PaymentRequestStatusEnum.PAID.getCode());
        paymentRequestDO.setLoaningDate(LocalDateTime.now());

        PaymentRequestQuery paymentRequestQuery = new PaymentRequestQuery();
        paymentRequestQuery.createCriteria().andOrderNoEqualTo(paymentDetailBO.getOrderNo());
        if (paymentRequestExtMapper.updateByQuerySelective(paymentRequestDO, paymentRequestQuery) != 1){
            throw new SuzukiCommonException(ErrorCodeEnum.INSERT_OR_UPDATA_ERROR);
        }
        /**调用提交流程接口**/
        applyService.saveOrderAudit(submitTaskBO,logedUser);
        return result;
    }


    /**
     * 判断当前状态是否处于垫款前或垫款后
     * @param orderNo
     * @return
     */
    @Override
    public Boolean isOrderStatuByPayment(String orderNo) throws SuzukiCommonException{
        /**查询订单存在的垫款申请状态是否处于已垫款**/
        log.info("正在查询垫款申请记录...");
        PaymentRequestDO paymentRequestInfo = paymentRequestManager.selectByOrderNo(orderNo);
        if(paymentRequestInfo != null){
            int applyStatus = paymentRequestInfo.getApplyStatus();
            if(applyStatus == PaymentRequestStatusEnum.PAID.getCode()){
                /**处于已垫款**/
                return true;
            }
        }
        return false;
    }

}
